from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request

from info.models import User, News,Category
from info import constants, db
from info.models import Category
from info.modules.profile import profile_blu
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    p = request.args.get("p",1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p =1

    user = g.user
    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        follows = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []
    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())

    data = {
        "users":user_dict_li,
        "total_page":total_page,
        "current_page":current_page
    }
    return render_template('news/user_follow.html', data=data)


@profile_blu.route('/news_list')
@user_login_data
def user_news_list():

    page = request.args.get("p",1)

    # 判断参数
    try:
        page = int(page)
    except Exception as e:
            current_app.logger.error(e)
            page = 1

    user = g.user
    news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
            current_app.logger.error(e)

    news_dict_list = []

    for news in news_list:
        news_dict_list.append(news.to_review_dict())
    data = {
        "news_list":news_dict_list,
        "total_page":total_page,
        "current_page":current_page
    }


    return render_template('news/user_news_list.html', data=data)

@profile_blu.route('/news_release', methods=["POST", "GET"])
@user_login_data
def news_release():
    if request.method == "GET":
        categories = []

        try:
            # 获取所有分类数据
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        # 保存分类数据并创建列表保存起来
        categories_dicts = []

        for category in categories:
            # 获取字典
            cate_dict = category.to_dict()
            # 拼接字典
            categories_dicts.append(cate_dict)

        # 移除’最新‘分类
        categories_dicts.pop(0)

        # 返回内容

        return render_template("news/user_news_release.html", data={"categories":categories_dicts})

    # POST请求
    title = request.form.get("title")
    source = "个人发布"
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    # 校验参数
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 读取图片
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 标题图片上传七牛
    try:
        key = storage(index_image)
    except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="图片上传错误")

    # 初始化新闻模型，设置数据
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id

    # 显示1代表带审核状态
    news.status = 1

    # 保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 返回结果
    return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


@profile_blu.route('/collection')
@user_login_data
def user_collection():
    # 获取页数
    page = request.args.get("p", 1)

    # 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 查询用户指定页数的收藏的新闻
    user = g.user

    news_list = []
    total_page = 1
    current_page = 1

    try:
        paginate = user.collection_news.paginate(page,constants.USER_COLLECTION_MAX_NEWS)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_list_li = []
    for news in news_list:
        news_list_li.append(news.to_basic_dict())

    data = {
        "total_page":total_page,
        "current_page":current_page,
        "collections":news_list_li
    }

    return render_template('news/user_collection.html', data=data)

@profile_blu.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pass_info.html')

    # 获取参数
    old_password = request.json.get("old_password")
    news_password = request.json.get("new_password")

    # 校验参数
    if not all([old_password, news_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 判断密码是否正确
    user = g.user
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")

    # 更改密码

    user.password = news_password

    return jsonify(errno=RET.OK, errmsg="保存成功")


@profile_blu.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html',data={"user":g.user.to_dict()})
    #  POST时修改头像
    # 取到上传的图片
    try:
        avatar = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 上传图片

    try:
        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传头像失败")

    # 保存图片地址
    user.avatar_url = key
    return jsonify(errno=RET.OK, errmsg="OK", data={"avatar_url":constants.QINIU_DOMIN_PREFIX+key})


@profile_blu.route('/base_info', methods=["GET", "POST"])
@user_login_data
def base_info():
    if request.method == "GET":
        return render_template('news/user_base_info.html',data={"user":g.user.to_dict()})

    # 代表是修改用户数据
    # 1.取到参数
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")

    # 2.校验参数

    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if gender not in ("WOMAN","MAN"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    user = g.user
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    return jsonify(errno=RET.OK, errmsg="OK")


@profile_blu.route('/info')
@user_login_data
def user_info():
    user = g.user
    if not user:
        # 代表没有登录，重定向到首页
        return redirect("/")
    data = {"user":user.to_dict()}

    return render_template("news/user.html",data=data)